﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Main.Packets
{
    /// <summary>
    /// Paquet de connexion (Demande ou confirmation)
    /// </summary>
    public class ConnectionPacket : Packet
    {
        private byte adresseSource;
        private byte adresseDestination;

        //public ConnectionPacket() { }

        private ConnectionPacket(byte numeroConnexion, PacketType type, byte source, byte destination)
            : base(numeroConnexion, type)
        {
            this.adresseSource = source;
            this.adresseDestination = destination;
        }

        #region Propriétés

        [JsonProperty(Order = 10)]
        public byte AdresseSource
        {
            get { return adresseSource; }
            set { adresseSource = value; }
        }

        [JsonProperty(Order = 20)]
        public byte AdresseDestination
        {
            get { return adresseDestination; }
            set { adresseDestination = value; }
        }

        #endregion

        /// <summary>
        /// Instanciation d'un paquet de demande de connexion
        /// </summary>
        public static ConnectionPacket CreateRequestConnectionPacket(byte numeroConnexion, byte source, byte destination)
        {
            ConnectionPacket packet = new ConnectionPacket(numeroConnexion, PacketType.CreateTypeForConnectionRequestPacket(), source, destination);
            return packet;
        }

        /// <summary>
        /// Instanciation d'un paquet de confirmation de connexion
        /// </summary>
        public static ConnectionPacket CreateConnectionConfirmationPacket(byte numeroConnexion, byte source, byte destination)
        {
            ConnectionPacket packet = new ConnectionPacket(numeroConnexion, PacketType.CreateTypeForConnectionConfirmationPacket(), source, destination);

            return packet;
        }

        /// <summary>
        /// Instanciation d'un paquet de connection (demande ou confirmation) à partir d'une ligne reçue d'une couche supérieure ou inférieure
        /// </summary>
        public static ConnectionPacket CreateConnectionPacket(string str)
        {
            return JsonConvert.DeserializeObject<ConnectionPacket>(str) as ConnectionPacket;
        }

        /// <summary>
        /// Envoie d'un paquet de connexion (demande ou confirmation) vers le flux passé en paramètre.
        /// </summary>
        /// <param name="sw"></param>
        public override void Send(System.IO.StreamWriter sw)
        {
            sw.WriteLine(JsonConvert.SerializeObject(this));
        }

        public override string ToString()
        {
            return base.ToString() + "Adresse source : "+this.adresseSource + "adresse destination : " + this.adresseDestination;
        }
    }
}
